import net.spreadshirt.util.Observer;
import net.spreadshirt.util.Observable;
import net.spreadshirt.logger.Logger;
import net.spreadshirt.logger.LogMessage;

/**
 * An observer of the Logger class. This class displays
 * messages sent to the log in an on-screen text field.
 */
class net.spreadshirt.logger.TextFieldView implements Observer {

	// The log that this object is observing.
	private var log:net.spreadshirt.logger.Logger;
	// A reference to the text field.
	private var out:TextField;
	private var out_format:TextFormat;

	/**
	 * TextFieldView Constructor
	 */
	public function TextFieldView(
		l:net.spreadshirt.logger.Logger,
		target:MovieClip,
		depth:Number,
		x:Number,
		y:Number,
		w:Number,
		h:Number
	) {
		log = l;
		makeTextField(target, depth, x, y, w, h);
	}

	/**
	 * Invoked when the log changes. For details, see the
	 * Observer interface.
	 */
	public function update(o:Observable, infoObj:Object):Void {
		// Cast infoObj to a LogMessage instance for type checking.
		var logMsg:LogMessage = LogMessage(infoObj);
		// Display the log message in the log text field.
		out.text += Logger.getLevelDesc(logMsg.getLevel()) +": "
			+ logMsg.getMessage() +"\n";
		// Set the text format
		out.setTextFormat(out_format);
		// Scroll to the bottom of the log text field.
		out.scroll = out.maxscroll;
	}

	/**
	 * Creates a text field in the specified movie clip at
	 * the specified depth. Log messages are displayed in the text field.
	 */
	public function makeTextField(
		target:MovieClip,
		depth:Number,
		x:Number,
		y:Number,
		w:Number,
		h:Number
	):Void {
		target.createTextField("log_txt", depth, x, y, w, h);
		out = target.log_txt;
		out.border = false;
		out.wordWrap = false;
		out.selectable = true;
		out.textColor = 0xcccccc;
		out_format = new TextFormat();
		out_format.font = "Arial";
		out_format.size = 10;
	}

	public function destroy():Void {
		log.removeObserver(this);
		out.removeTextField();
	}

}
